package com.example.main;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class Main05 {

    private final static AtomicBoolean EXECUTE=new AtomicBoolean(true);

    public static void main(String[] args) {

        new Thread(new Task()).start();
        new Thread(new Task()).start();
        new Thread(new Task()).start();
    }

    public static void doSomething(){

        if (EXECUTE.compareAndSet(true,false)){
            System.out.println(Thread.currentThread()+" : 执行步骤1");
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread()+" : 执行步骤1完成");
        }else {
            long start = System.currentTimeMillis();
            while (!EXECUTE.get()){
                System.out.println(Thread.currentThread()+" : 等待步骤1执行完成");
                try {
                    TimeUnit.MILLISECONDS.sleep(200);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                if (System.currentTimeMillis()-start>60000){
                    break;
                }
            }
            System.out.println(Thread.currentThread()+" : 其他线程执行步骤1完成");
        }
        EXECUTE.set(true);

        System.out.println(Thread.currentThread()+" : 执行步骤2");
    }


    public static class Task implements Runnable{
        @Override
        public void run() {
            doSomething();
        }
    }
}
